package com.appkudos.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.appkudos.controller.UserController;
import com.appkudos.model.Group;
import com.appkudos.model.User;
import com.appkudos.view.R;
import android.app.Activity;
import android.os.Bundle;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.SimpleCursorAdapter;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class AddFriendActivity extends Activity implements OnClickListener, ViewBinder{
    ListView lv;
    Button findButton;
    EditText search_box;
    TextView search_label;
    TextView search_term;
    UserController uc;
    Cursor cur;
    User user;
	private Activity PARENTACTIVITY; 
	List<User> existing_friends;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_add_friend);
        PARENTACTIVITY = this;
        
        Intent launchIntent = getIntent();
        Bundle extras = launchIntent.getExtras();
        uc = new UserController();
        user = uc.getCurrentUser(extras);
        
      
             
   }
    
    private void initWidget(){
    	search_box = (EditText) this.findViewById(R.id.af_friend_search);
  	    search_label = (EditText) this.findViewById(R.id.af_search_label);
  	    search_term = (EditText) this.findViewById(R.id.af_search_term);
  	    
  	    search_label.setVisibility(View.GONE);
  	    search_term.setVisibility(View.GONE);
        	    
        // get listview from layout
    	lv=(ListView)findViewById(R.id.af_friend_list);
    	    
    	// open a new page when add friend is clicked
    	findButton = (Button) this.findViewById(R.id.af_find);
        findButton.setOnClickListener(this);  	    // open a new page when add friend is clicked  
    }

	@Override
	public void onClick(View arg0) {		  
		search_label.setVisibility(View.VISIBLE);
  	    search_term.setVisibility(View.VISIBLE);
  	    
	      String keyword = search_box.getText().toString();
//	      Toast.makeText(getApplicationContext(), "keyword is "+keyword,Toast.LENGTH_LONG).show();
	      search_term.setText(keyword);
	      
	      // get existing friends of user
	      existing_friends = uc.getFriendsOfUser(user.getUsername());

	      // get users that match the search keyword
	      List<User> matched_users = uc.searchForUser(keyword) ;
    
		  // display list of matched users
		  if(matched_users.size() == 0)
			    Toast.makeText(getApplicationContext(), "No matched user",Toast.LENGTH_LONG).show();
		  else{
			  	displayMatchedUsers(matched_users);
//				Toast.makeText(getApplicationContext(), "u:"+matched_users.get(0).getFirstname(),Toast.LENGTH_SHORT).show();
				lv.setVisibility(View.VISIBLE);
		  }
	}

	// helper method to display matched users 
	private void displayMatchedUsers(List list){
	  	Map<String, User> itemData;
	  	User matched;
	  	List<Map<String, User>> listData = new ArrayList<Map<String, User>>();
	  	
	  	// put the groups into a hashmap (used for input by simple adapter)
	  	for(int j=0; j<list.size();j++){
	  		itemData = new HashMap<String, User>(1);
	  		matched = (User) list.get(j);
	  		itemData.put("add_button", matched);
	  		listData.add(itemData);
	  	}    
	
	  	// bind simple adapter to the list view
	      SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData, R.layout.two_column_item,
	              new String[] {
	                  "add_button"
	              }, new int[] {
	                  R.id.add_button
	              });
	      
	      // bind viewBinder to adapter and set adapter to listview
	      simpleAdapter.setViewBinder(this);
	      lv.setAdapter(simpleAdapter);
	  }
	
  // check if the user is already friends with matched user
  private boolean checkExistingFriend(User matched){
	  boolean existed = false;
	  if(matched.getUsername().compareTo(user.getUsername()) == 0){
		  existed = true;
		  return existed;
	  }
	  
	  for (int i=0; i<existing_friends.size();i++){
		  if(existing_friends.get(i).getUsername().compareTo(matched.getUsername()) == 0){
			  existed = true;
			  return existed;
		  }     
	  }
	  return existed;
  }
  
//  public void CustomizedToast(Context context, String text, int duration){
//	  LayoutInflater inflater = getLayoutInflater();
//	  View layout = inflater.inflate(R.layout.toast,
//	                                 (ViewGroup) findViewById(R.id.toast_layout_root));
//	
//	  ImageView image = (ImageView) layout.findViewById(R.id.toast_image);
//	  image.setImageResource(R.drawable.ic_button_star);
//	  TextView toast_text = (TextView) layout.findViewById(R.id.toast_text);
//	  toast_text.setText(text);
//	
//	  Toast toast = new Toast(getApplicationContext());
//	  toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
//	  toast.setDuration(Toast.LENGTH_LONG);
//	  toast.setView(layout);
//	  toast.show();
//  }
  
  @Override
  public boolean setViewValue(View view, Object data, String stringRepresetation) {  	
	  	  // get data for the row
	  	  User matched = (User) data;
	      CheckedTextView ck = (CheckedTextView) view;
	      
	      // bind the matched user to textView
	      ck.setText(matched.getUsername());
	      
	      // check if user is an existing friend or is the same person
	      if(checkExistingFriend(matched)){
	    	  ck.setChecked(true);
	      }else{
	    	  ck.setChecked(false);
	      }

	      ck.setOnClickListener(new View.OnClickListener() {
	          public void onClick(View v)
	          {
	        	   CheckedTextView ckbox = (CheckedTextView) v;
	        	   String friend = ckbox.getText().toString();
	 	           
	        	   if(user.getUsername().compareTo(friend) == 0){
	        		   Toast.makeText(getApplicationContext(), "No matched user",Toast.LENGTH_LONG).show();
//	        		   CustomizedToast(getApplicationContext(), "You cannot add yourself as friend",Toast.LENGTH_LONG);
	   	           }else if(!ckbox.isChecked()){
	 	        	   ckbox.toggle();
	 	        	   uc.addFriend(user.getUsername(),friend);
	 	        	  Toast.makeText(getApplicationContext(), "User "+ friend+" has been added to your friends",Toast.LENGTH_LONG).show();
//	 	        	   CustomizedToast(getApplicationContext(), ""+ friend+" has been added to your friends",Toast.LENGTH_LONG);
	 	           }else if(ckbox.isChecked()){
	 	        	  Toast.makeText(getApplicationContext(), "You are already a friend of "+friend,Toast.LENGTH_LONG).show();
//	 	        	   CustomizedToast(getApplicationContext(), "You are already a friend of "+friend,Toast.LENGTH_LONG);
	   	           }
	 	           	    
	          }
	      });

	      return true;
  }
}
